
package org.netty.message.server;

import org.netty.message.gper.code.GpDecode;
import org.netty.message.gper.code.GpEncode;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServer {
	
	public static void main(String[] args) {
		
		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup work = new NioEventLoopGroup();
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(boss, work)
			.channel(NioServerSocketChannel.class)
			.childHandler(new ChannelInitializer<SocketChannel>() {

				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					// TODO Auto-generated method stub
					ch.pipeline()
						//如果5秒没有读事件，触发心跳检测
						.addLast(new IdleStateHandler(5, 0, 0))
						.addLast(new GpDecode())
						.addLast(new GpEncode())
						.addLast(new ServerHandler());
				}
			});
		
		try {
			ChannelFuture channelFuture = serverBootstrap.bind(9000).sync();
			log.info("ProtocolServer start success {9000}");
			channelFuture.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			boss.shutdownGracefully();
			work.shutdownGracefully(); 
		}
		
	}

}
